﻿using UnityEngine;

namespace Assets.Scripts
{
    public class MouseDownMove:MonoBehaviour
    {
        private Rigidbody _rb;
        private Animator _animator;
        private Vector3 _targetPos;
        private Vector3 _direction;
        [SerializeField]private float _rotateSpeed;
        
        [SerializeField]private float _moveSpeed;

        private void Start()
        {
            _rb = GetComponent<Rigidbody>();
            _animator = GetComponent<Animator>();   
            _targetPos = transform.position;
        }
        public void Rotate(Vector3 direction) 
        {
            direction.y = 0;
            Vector3 targetForward = Vector3.RotateTowards(transform.forward, direction.normalized, _rotateSpeed * Time.deltaTime, .01f);
            Quaternion newRotation = Quaternion.LookRotation(targetForward);
            transform.rotation = newRotation;
        }

        public void MoveTo(Vector3 targetPos) 
        {
            Vector3 direction;
            targetPos.y = 0;
            Vector3 currentPos = new Vector3(transform.position.x,0,transform.position.z);
            if ((targetPos - currentPos).magnitude <= 0.1f) 
            {
                direction = Vector3.zero;
                _rb.velocity = new Vector3(0, _rb.velocity.y, 0); ;
            }
            else 
            {
                direction = targetPos - currentPos;
                direction.Normalize();
                Vector3 targetPosition = _rb.position + direction * _moveSpeed * Time.deltaTime;
                Vector3 targetVelocity = (targetPosition - transform.position) / Time.deltaTime;
                _rb.velocity = new Vector3(targetVelocity.x, _rb.velocity.y, targetVelocity.z);
            }
            _animator.SetFloat("VerticalSpeed",direction.magnitude*_moveSpeed,0.1f,Time.deltaTime);
        }

        private void Update()
        {
            if (Input.GetMouseButtonDown(0)) 
            {
                Ray ray =Camera.main.ScreenPointToRay(Input.mousePosition);
                Plane hitPlane = new Plane(Vector3.up, transform.position);
                if(hitPlane.Raycast(ray,out float distance)) 
                {
                    _targetPos=ray.GetPoint(distance);
                }
            }
        }

        private void FixedUpdate()
        {
             _direction=_targetPos-transform.position;
            Rotate(_direction);
            MoveTo(_targetPos);
        }

       
    }
}
